import db from "../models/index.js";
import {Op} from "sequelize";

let category = db.category;
let categoryDao = {};

// 创建私人账单分类 is_out 0收入 1支出
categoryDao.addUserCategory = async (name, user_id, is_out, t) => {
  return category.create({
    name, user_id, is_out
  }, {transaction: t});
};

// 创建公司账单分类 is_out 0收入 1支出
categoryDao.addCompanyCategory = async (name, company_id, is_out, t) => {
  return category.create({
    name, company_id, is_out
  }, {transaction: t});
};

// 增加公司默认账单分类
categoryDao.addCompanyDefaultCategory = async (id, name, is_out, t) => {
  return category.create({
    id, name, company_id: 0, is_out
  }, {transaction: t});
};

// 增加私人默认账单分类
categoryDao.addUserDefaultCategory = async (id, name, is_out, t) => {
  return category.create({
    id, name, is_out, user_id: 0
  }, {transaction: t});
};

// 删除账单分类
categoryDao.deleteCategory = async (id, t) => {
  return category.destroy({
    where: {
      id
    },
    transaction: t
  });
};

// 获取用户账单分类
categoryDao.getUserCategory = async (user_id, t) => {
  let userIds = [0, user_id];
  return category.findAll({
    where: {
      user_id: {
        [Op.in]: userIds,
      },
      company_id: null
    },
    raw: true,
    transaction: t
  });
};

// 获取公司账单分类
categoryDao.getCompanyCategory = async (company_id, t) => {
  let companyIds = [company_id, 0];
  return category.findAll({
    where: {
      company_id: {
        [Op.in]: companyIds
      },
      user_id: null
    },
    raw: true,
    transaction: t
  });
};

// 获取这个分类的数据
categoryDao.getCategoryData = async (id, t) => {
  return category.findOne({
    where: {
      id
    },
    raw: true,
    transaction: t
  });
};

// 获取用户这个名称的分类数据
categoryDao.getPersonCategoryDataByName = async (name, user_id, t) => {
  let userIds = [0, user_id];
  return category.findOne({
    where: {
      name,
      user_id: {
        [Op.in]: userIds
      }
    },
    raw: true,
    transaction: t
  });
};

// 获取这个分类id是否属于这个用户
categoryDao.getPersonCategoryByUserId = async (id, user_id, t) => {
  return category.findOne({
    where: {
      id,
      user_id
    },
    raw: true,
    transaction: t
  });
};

// 获取公司的这个名称分类数据
categoryDao.getCompanyCategoryDataByName = async (name, company_id, t) => {
  return category.findOne({
    where: {
      name,
      company_id
    },
    raw: true,
    transaction: t
  });
};

export default categoryDao;

